<template>
    <div class="qr_code_login">
        <top-timer :second="countdown"/>
        <template v-if="isError">
            <div class="center err_box">
                <img src="@/assets/img/error_icon.png" alt="">
                <p class="font_M font_40 col_333">扫码失败</p>
                <el-button type="primary" class="col_fff font_M">使用手机号码开箱</el-button>
            </div>
        </template>
        <template v-if="codeLogin">
            <p class="font_40 col_333 font_M title center">请扫描下方二维码</p>
            <div class="center">
                <!--<img src="@/assets/img/code.png" width="500" height="500" alt="">-->
                <vue-qr :text="qrCode" :size="250"/>
            </div>
            <p class="col_888 font_36 tip center">支持微信、麦智克微信小程序扫描</p>
            <div class="btn col_blue font_40 center" @click="changeLoginModel()">手机号开箱</div>
        </template>
        <template v-if="phoneLogin">
            <p class="font_40 col_333 font_M title center">使用手机号开箱</p>
            <div class="form">
                <div class="flex">
                    <div class="border1" v-if="keyboard.borderNum==='01'"></div>
                    <!--<el-input v-model="phone" placeholder="账号"></el-input>-->
                    <el-input class="phone" placeholder="账号" v-model="phone" readonly="readonly"
                              data-layout="numeric"
                              @focus="show($event,'01')" :class="keyboard.borderChecked==='01'?'input_checked':''"/>
                    <vue-touch-keyboard :options="keyboard.options" v-if="keyboard.visible" :layout="keyboard.layout" :cancel="hide"
                                        :accept="accept" :input="input"/>
                </div>
                <div class="flex">
                    <div class="border1" v-if="keyboard.borderNum==='02  '"></div>
                    <!--<el-input class="flex1" v-model="kaptcha" placeholder="验证码"></el-input>-->
                    <el-input placeholder="图片验证码" v-model="kaptcha" readonly="readonly" data-layout="compact"
                              @focus="show($event,'02')" :class="keyboard.borderChecked==='02'?'input_checked':''"/>
                    <vue-touch-keyboard :options="keyboard.options" v-if="keyboard.visible" :layout="keyboard.layout" :cancel="hide"
                                        :accept="accept" :input="input"/>
                    <div>
                        <img @click="getKaptcha()" :src="imgSrc" alt="">
                    </div>
                </div>
                <div class="flex">
                    <div class="border1" v-if="keyboard.borderNum==='03'"></div>
                    <!--<el-input class="flex1" v-model="checkCode" placeholder="验证码"></el-input>-->
                    <el-input placeholder="短信验证码" v-model="checkCode" readonly="readonly" data-layout="numeric"
                              @focus="show($event,'03')" :class="keyboard.borderChecked==='03'?'input_checked':''"/>
                    <vue-touch-keyboard :options="keyboard.options" v-if="keyboard.visible" :layout="keyboard.layout" :cancel="hide"
                                        :accept="accept" :input="input"/>
                    <div class="captcha_btn col_blue font_36 font_M center" @click="!actBtn?getCheckMsgCode():''"
                         :class="actBtn? 'act_btn' : ''">
                        {{actBtn? `(${timeVal})重新发送`:'获取验证码'}}
                    </div>
                </div>
                <el-button type="primary" class="col_fff font_M" @click="handleConfirm()">确认</el-button>
            </div>
            <div class="btn col_blue font_40 center" @click="changeLoginModel()">二维码开箱</div>
        </template>
        <top-tips/>
    </div>
</template>

<script>
  import VueQr from 'vue-qr';
  import ReconnectingWebSocket from 'reconnecting-websocket';

  export default {
    components: {VueQr},
    name: 'qr-code-login',
    data() {
      return {
        phone: '',
        kaptcha: '',
        tempToken: '',
        checkCode: '',
        imgSrc: '',
        isError: false,
        codeLogin: true,
        phoneLogin: false,
        actBtn: false,
        timeVal: 60,
        qrCode: '',
        initTimer: Object,
        rws:null,
        countdown:300,
        keyboard:{
          visible: false,
          layout: 'compact',
          input: null,
          borderNum: '',
          borderChecked:'',
          options:{
            useKbEvents: false,
            preventClickEvent: false,
          }
        }
      };
    },
    created() {
      this.getQrCode();
      this.initWebSocket();
    },
    destroyed() {
      this.rws.close()
    },
    mounted() {
      this.initTimer = () => {
        this.$children[0].initTimer();
      };
    },
    methods: {
      accept (text) {
        this.hide()
      },

      show (e, borderNum) {
        this.keyboard.borderNum = borderNum
        this.keyboard.borderChecked = borderNum
        if (e.path[0].value !== '') {
          this.keyboard.borderNum = ''
        }
        this.input = e.target
        this.keyboard.layout = e.target.dataset.layout
        if (!this.keyboard.visible)
          this.keyboard.visible = true
      },
      getQrCode() {
        this.$axios.get('cabLoginRest/getQRCode', {
          params: {
            qrType: '01',
            second: this.countdown
          },
        }).then(res => {
          this.qrCode = res.data;
        });
      },
      changeLoginModel() {
        this.codeLogin = !this.codeLogin;
        this.phoneLogin = !this.phoneLogin;
        this.initTimer();
        this.getKaptcha();
      },
      onStop() {
        this.$router.back();
      },
      initWebSocket: function() {
        // WebSocket与普通的请求所用协议有所不同，ws等同于http，wss等同于https
        const cabinetId = localStorage.getItem('cabinetId');
        let ws_url = `${this.$global.WS_API}cabWebSocket/${cabinetId}`;
        this.rws = new ReconnectingWebSocket(ws_url);
        this.rws.addEventListener('open', () => {
          this.rws.send('scan!');
        });
        this.rws.addEventListener('message', (e) => {
          let data = JSON.parse(e.data);
          localStorage.setItem('token', data.obj.token);
          this.$router.push('Cupboard');
        });
      },
      getKaptcha() {
        this.$axios.get('captchaRest/getTempToken').then(res => {
          if (res.data.result) {
            this.tempToken = res.data.msg;
            this.imgSrc = this.$global.API + 'captchaRest/getValidateImg?tempToken=' + this.tempToken;
          }
        });
      },
      phoneKaptcha() {
        let self = this;
        self.actBtn = true;
        let fan = setInterval(function() {
          self.timeVal--;
          if (self.timeVal <= 0) {
            clearInterval(fan);
            self.actBtn = false;
            self.timeVal = 60;
          }
        }, 1000);
      },
      getCheckMsgCode() {
        if (this.actBtn) {
          return;
        }
        if (!this.phone) {
          this.$alert('请输入账号', '提示', {
            confirmButtonText: '确定',
          });
          return;
        }
        if (!this.kaptcha) {
          this.$alert('请输入图片验证码', '提示', {
            confirmButtonText: '确定',
          });
          return;
        }
        this.$axios.get('regRest/getCheckMsgCode', {
          params: {
            phone: this.phone,
            type: '03',
            tempToken: this.tempToken,
            kaptcha: this.kaptcha,
          },
        }).then((res) => {
          this.phoneKaptcha();
          if (res.data.result) {
            this.$message.success('发送成功');
          } else {
            this.$alert(res.data.msg, '错误提示', {
              confirmButtonText: '确定',
            });
            this.getKaptcha();
          }
        });
      },
      handleConfirm() {
        if (!this.phone) {
          this.$alert('请输入账号', '提示', {
            confirmButtonText: '确定',
          });
          return;
        }
        if (!this.kaptcha) {
          this.$alert('请输入图片验证码', '提示', {
            confirmButtonText: '确定',
          });
          return;
        }
        if (!this.checkCode) {
          this.$alert('请输入短信验证码', '提示', {
            confirmButtonText: '确定',
          });
          return;
        }
        this.$axios.post('cabLoginRest/userRegAndLogin', {
          phone: this.phone,
          type: '03',
          checkCode: this.checkCode,
        }).then((res) => {
          if (res.data.result) {
            localStorage.setItem('token', res.data.obj.token);
            this.$router.push('Cupboard');
          } else {
            this.$alert(res.data.msg, '登录错误', {
              confirmButtonText: '确定',
            });
            this.kaptcha = '';
            this.getKaptcha();
          }
        });
      },
    },
  };
</script>

<style lang="scss">
    .qr_code_login {
        .title {
            margin: 0.40rem auto 0.60rem;
        }

        .tip {
            margin: 0.20rem auto 0.98rem;
        }

        .btn {
            margin: auto;
            width: 3.00rem;
            height: 0.80rem;
            line-height: 0.78rem;
            background: rgba(255, 255, 255, 1);
            box-shadow: 0rem 0.02rem 0.04rem 0rem rgba(10, 130, 236, 0.2);
            border-radius: 0.51rem;
            border: 0.02rem solid rgba(0, 128, 244, 1);
        }

        .err_box {
            margin-top: 0.80rem;

            img {
                margin-bottom: 0.40rem;
            }

            .err_content {
                margin-top: 0.20rem;
            }

            button {
                margin-top: 3.17rem;
                width: calc(100% - 1.60rem);
                height: 1.20rem;
                font-size: 0.50rem;
                border-radius: 0.70rem;
                background-color: #0A82EC;
            }
        }

        .form {
            padding: 0 0.80rem;

            .flex {
                align-items: flex-end;
                position: relative;
                .border1 {
                    position: absolute;
                    height: 0.4rem;
                    border-left: 1px solid #000;
                    top: 0.8rem;
                    z-index: 99;
                    left: 0.3rem;
                }
            }

            .el-input {
                margin-top: 0.40rem;
                border-radius: 0.16rem;
                background-color: #ECF5FC;
                overflow: hidden;
                border: 1px solid transparent;
            }

            input {
                padding: 0 0.40rem;
                border: none;
                background-color: #ECF5FC;
                line-height: 1.20rem;
                height: 1.20rem;
                font-size: 0.36rem;

                &::placeholder {
                    color: #999999;
                }
            }
            .input_checked{
                border:1px solid #0a82ec;
            }

            .captcha_btn {
                border-radius: 0.16rem;
                width: 3.00rem;
                height: 1.20rem;
                line-height: 1.20rem;
                background-color: #ECF5FC;
                margin-left: 0.40rem;
            }

            img {
                box-sizing: border-box;
                width: 3.00rem;
                height: 1.20rem;
                background: rgba(255, 255, 255, 1);
                border-radius: 0.16rem;
                border: 0.02rem solid rgba(224, 224, 224, 1);
                margin-left: 0.40rem;
            }

            button {
                width: 100%;
                height: 1.20rem;
                font-size: 0.50rem;
                border-radius: 0.70rem;
                background-color: #0A82EC;
                margin-top: 0.80rem;
                margin-bottom: .50rem;
            }

            .act_btn {
                color: #999999;
            }
        }
    }
</style>
